import { h, Fragment } from "preact";
import { useEffect, useRef } from "preact/hooks";
import { Handlers, PageProps } from "$fresh/server.ts";
import { signal } from "@preact/signals";
import { getDbClient } from "../../../../utils/db.ts";
import HeadComponent from "../../../../components/Head.tsx";
import Button from "../../../../components/Button.tsx";
import { AdminState } from "../../../_middleware.ts";

interface Post {
  id: number;
  title: string;
  content: string;
  created_at: string;
}

// 创建一个信号存储文章内容
export const editorContent = signal("");

// 处理程序确保只有管理员可以访问此页面
export const handler: Handlers<Post | null, AdminState> = {
  async GET(req, ctx) {
    // 重定向非管理员用户
    if (!ctx.state.isAdmin) {
      const headers = new Headers();
      headers.set("location", `/admin/login?redirect=/admin/posts/${ctx.params.id}/edit`);
      return new Response(null, { status: 303, headers });
    }

    // 获取文章数据
    const id = ctx.params.id;
    let client;

    try {
      client = await getDbClient();
      const result = await client.query(
        "SELECT id, title, content, created_at FROM posts WHERE id = ?",
        [id]
      );

      if (result.length === 0) {
        return ctx.render(null);
      }
      
      // 设置文章内容到信号中
      const post = result[0] as Post;
      editorContent.value = post.content;
      
      return ctx.render(post);
    } catch (error) {
      console.error("获取文章数据时出错:", error);
      return ctx.render(null);
    } finally {
      if (client) await client.close();
    }
  },
  
  async POST(req, ctx) {
    // 验证管理员身份
    if (!ctx.state.isAdmin) {
      return new Response("未授权", { status: 403 });
    }
    
    const id = ctx.params.id;
    const form = await req.formData();
    const title = (form.get("title") as string || "").trim();
    const content = (form.get("content") as string || "").trim();
    
    console.log(`准备更新文章 ID: ${id}`);
    console.log(`标题长度: ${title.length}, 内容长度: ${content.length}`);
    
    if (!title || !content) {
      const headers = new Headers();
      headers.set("location", `/admin/posts/${id}/edit?error=${encodeURIComponent("标题和内容不能为空")}`);
      return new Response(null, { status: 303, headers });
    }
    
    let client;
    try {
      client = await getDbClient();
      
      // 检查文章是否存在
      const checkResult = await client.query("SELECT id FROM posts WHERE id = ?", [id]);
      if (checkResult.length === 0) {
        console.error(`文章不存在，ID: ${id}`);
        const headers = new Headers();
        headers.set("location", `/admin/posts/${id}/edit?error=${encodeURIComponent("文章不存在")}`);
        return new Response(null, { status: 303, headers });
      }
      
      console.log("开始执行更新操作");
      
      // 更新文章
      await client.execute(
        "UPDATE posts SET title = ?, content = ?, updated_at = NOW() WHERE id = ?",
        [title, content, id]
      );
      
      console.log("更新成功");
      
      // 重定向到成功页面
      const headers = new Headers();
      headers.set("location", `/admin/posts?updated=true`);
      return new Response(null, { status: 303, headers });
    } catch (error) {
      console.error("更新文章时出错:", error);
      console.error("错误详情:", JSON.stringify(error, null, 2));
      
      // 创建一个带有更具体错误信息的URL
      let errorMsg = "更新文章失败";
      if (error instanceof Error) {
        errorMsg += `: ${error.message}`;
      }
      
      const headers = new Headers();
      headers.set("location", `/admin/posts/${id}/edit?error=${encodeURIComponent(errorMsg)}`);
      return new Response(null, { status: 303, headers });
    } finally {
      if (client) await client.close();
    }
  }
};

export default function EditPostPage({ data: post, state, url }: PageProps<Post | null, AdminState>) {
  const { isAdmin, adminNickname, adminAvatarUrl } = state;
  const error = url.searchParams.get("error");
  
  // 错误处理
  if (!post) {
    return (
      <>
        <HeadComponent title="文章未找到" description="无法编辑不存在的文章">
          <link rel="stylesheet" href="/styles.css" />
          <link rel="stylesheet" href="/article-styles.css" />
        </HeadComponent>
        
        <div class="article-container flex flex-col min-h-screen">
          <header class="article-header-glass sticky top-0 z-50">
            <div class="container mx-auto max-w-3xl py-3 px-4 md:px-0 flex items-center justify-between">
              <a href="/admin/posts" class="flex items-center space-x-2 text-gray-600 hover:text-blue-600 transition-colors duration-200">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                </svg>
                <span class="text-sm font-medium">返回文章列表</span>
              </a>
            </div>
          </header>
          
          <main class="flex-grow py-10 md:py-12 px-4 md:px-0 article-content">
            <div class="container mx-auto max-w-3xl bg-white p-6 md:p-10 rounded-lg shadow-subtle">
              <h1 class="text-3xl md:text-4xl font-bold text-gray-900 mb-6">文章未找到</h1>
              <p class="text-gray-600 mb-8">无法找到您要编辑的文章，请返回文章列表重试。</p>
              <Button href="/admin/posts" variant="primary">返回文章列表</Button>
            </div>
          </main>
        </div>
      </>
    );
  }

  // 设置初始内容
  if (post && post.content) {
    editorContent.value = post.content;
  }

  return (
    <>
      <HeadComponent title={`编辑: ${post.title}`} description="编辑博客文章">
        <link rel="stylesheet" href="/styles.css" />
        <link rel="stylesheet" href="/article-styles.css" />
        <link rel="stylesheet" href="/wangeditor/style.css" />
        <script src="/wangeditor/index.js"></script>

        <script dangerouslySetInnerHTML={{
          __html: `
            // 在页面加载完成后初始化编辑器
            document.addEventListener('DOMContentLoaded', () => {
              setTimeout(() => {
                if (typeof window.wangEditor === 'undefined') {
                  console.error('wangEditor未找到，可能脚本加载失败');
                  document.getElementById('editor-container').innerHTML = 
                    '<div class="p-4 text-red-500 text-center">富文本编辑器加载失败，请刷新页面重试</div>';
                  return;
                }

                try {
                  const { createEditor, createToolbar } = window.wangEditor;
                  
                  // 简化的编辑器配置，避免使用高级API
                  
                  // 获取编辑器容器和工具栏容器
                  const editorContainer = document.getElementById('editor-container');
                  const toolbarContainer = document.getElementById('toolbar-container');
                  
                  if (!editorContainer || !toolbarContainer) {
                    console.error('编辑器容器未找到');
                    return;
                  }
                  
                  // 创建编辑器 - 简化版
                  const editor = createEditor({
                    selector: editorContainer,
                    html: ${JSON.stringify(post.content)},
                    config: {
                      placeholder: '请输入文章内容...',
                      MENU_CONF: {
                        // 图片上传配置
                        uploadImage: {
                          // 基于 base64 编码的 dataUrl 形式上传图片
                          base64LimitSize: 5 * 1024 * 1024, // 限制 5M
                        }
                      }
                    }
                  });
                  
                  // 创建工具栏 - 简化版
                  createToolbar({
                    editor: editor,
                    selector: toolbarContainer,
                    config: {
                      toolbarKeys: [
                        'headerSelect',
                        'bold',
                        'italic',
                        'underline',
                        'through',
                        'fontSize',
                        'fontFamily',
                        'lineHeight',
                        'color',
                        'bgColor',
                        'bulletedList',
                        'numberedList',
                        'justifyLeft',
                        'justifyCenter',
                        'justifyRight',
                        'insertLink',
                        'uploadImage',
                        'insertTable',
                        'codeBlock',
                        'undo',
                        'redo',
                      ]
                    }
                  });
                  
                  // 基本的草稿保存功能
                  const LOCAL_STORAGE_KEY = 'wangeditor-draft-${post.id}';
                  
                  // 读取草稿
                  const savedContent = localStorage.getItem(LOCAL_STORAGE_KEY);
                  if (savedContent && savedContent !== editor.getHtml()) {
                    if (confirm('检测到有未保存的草稿，是否恢复？')) {
                      editor.setHtml(savedContent);
                    } else {
                      localStorage.removeItem(LOCAL_STORAGE_KEY);
                    }
                  }
                  
                  // 简化的自动保存功能
                  let timer;
                  editor.on('change', () => {
                    // 更新隐藏input
                    document.getElementById('content').value = editor.getHtml();
                    
                    // 计算字数
                    const text = editor.getText();
                    const wordCount = text.replace(/\\s+/g, '').length;
                    const countElem = document.getElementById('word-count');
                    if (countElem) {
                      countElem.textContent = '字数: ' + wordCount;
                    }
                    
                    // 清除之前的定时器
                    clearTimeout(timer);
                    
                    // 自动保存
                    timer = setTimeout(() => {
                      const content = editor.getHtml();
                      if (content && content.length > 10) {
                        localStorage.setItem(LOCAL_STORAGE_KEY, content);
                        
                        const statusElem = document.getElementById('editor-status');
                        if (statusElem) {
                          statusElem.textContent = '草稿已保存 - ' + new Date().toLocaleTimeString();
                          statusElem.style.opacity = '1';
                          setTimeout(() => { statusElem.style.opacity = '0.5'; }, 2000);
                        }
                      }
                    }, 5000);
                  });
                  
                  // 表单提交时清理草稿
                  document.querySelector('form').addEventListener('submit', function() {
                    localStorage.removeItem(LOCAL_STORAGE_KEY);
                  });
                  
                  // 添加清除草稿按钮功能
                  const clearDraftBtn = document.getElementById('clear-draft');
                  if (clearDraftBtn) {
                    clearDraftBtn.addEventListener('click', function() {
                      if (confirm('确定要清除所有草稿吗？')) {
                        localStorage.removeItem(LOCAL_STORAGE_KEY);
                        alert('草稿已清除');
                      }
                    });
                  }
                  
                } catch (error) {
                  console.error('初始化编辑器失败:', error);
                  document.getElementById('editor-container').innerHTML = 
                    '<div class="p-4 text-red-500 text-center">初始化编辑器失败: ' + error.message + '</div>';
                }
              }, 500); // 延迟初始化，确保DOM已完全加载
            });
          `
        }}></script>
      </HeadComponent>
      
      <div class="article-container flex flex-col min-h-screen">
        <header class="article-header-glass sticky top-0 z-50">
          <div class="container mx-auto max-w-3xl py-3 px-4 md:px-0 flex items-center justify-between">
            <a href="/admin/posts" class="flex items-center space-x-2 text-gray-600 hover:text-blue-600 transition-colors duration-200">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                <path stroke-linecap="round" stroke-linejoin="round" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
              </svg>
              <span class="text-sm font-medium">返回文章列表</span>
            </a>
          </div>
        </header>
        
        <main class="flex-grow py-10 md:py-12 px-4 md:px-0 article-content">
          <div class="container mx-auto max-w-3xl bg-white p-6 md:p-10 rounded-lg shadow-subtle">
            <h1 class="text-3xl md:text-4xl font-bold text-gray-900 mb-6">编辑文章</h1>
            
            {error && (
              <div class="mb-6 p-4 bg-red-50 text-red-600 rounded-md">
                {decodeURIComponent(error)}
              </div>
            )}
            
            <form method="POST" class="space-y-6">
              <div>
                <label for="title" class="block text-sm font-medium text-gray-700 mb-1">
                  文章标题
                </label>
                <input
                  type="text"
                  id="title"
                  name="title"
                  class="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  required
                  defaultValue={post.title}
                />
              </div>
              
              <div>
                <label for="editor-container" class="block text-sm font-medium text-gray-700 mb-1">
                  文章内容
                </label>
                <div class="rich-text-editor border border-gray-300 rounded-md overflow-hidden">
                  <div id="toolbar-container" class="border-b border-gray-300"></div>
                  <div id="editor-container" class="p-2" style="height: 500px"></div>
                  <div class="flex justify-between items-center px-3 py-2 bg-gray-50 border-t border-gray-300 text-xs text-gray-600">
                    <div id="editor-status" class="opacity-50 transition-opacity">准备就绪</div>
                    <div class="flex space-x-4">
                      <button type="button" id="clear-draft" class="text-blue-600 hover:text-blue-800">清除草稿</button>
                      <span id="word-count">字数: 0</span>
                    </div>
                  </div>
                </div>
                <input type="hidden" name="content" id="content" value={post.content} />
              </div>
              
              <div class="flex justify-end space-x-3 pt-4">
                <a
                  href="/admin/posts"
                  class="px-4 py-2 text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md transition-colors"
                >
                  取消
                </a>
                <button
                  type="submit"
                  class="px-4 py-2 text-white bg-blue-600 hover:bg-blue-700 rounded-md transition-colors"
                >
                  保存更改
                </button>
              </div>
            </form>
          </div>
        </main>
      </div>
    </>
  );
} 